package com.maigao.util;


import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {


    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doGet(String url, HttpHost proxy) {
        return doGet(url, null, proxy);
    }

    public static String doGet(String url, HashMap<String, String> headers, HttpHost proxy) {
        return doGet(new HttpGet(url), headers, proxy);
    }

    public static String doGet(HttpGet httpGet, HashMap<String, String> headers, HttpHost proxy) {
        try {
            HttpResponse httpResponse = doGetWithResponse(httpGet, headers, proxy);
            HttpEntity entity = httpResponse.getEntity();
            String content = entityToString(entity);
            EntityUtils.consume(entity);
            return content;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static void main(String[] args) {
//        System.out.println(getPicSign("https://maigao-data.oss-cn-shanghai.aliyuncs.com/1636793502840.jpg"));
//        System.out.println(getPicSign("https://maigao-data.oss-cn-shanghai.aliyuncs.com/1636793502840.jpg"));
//        System.out.println(getPicSign("https://maigao-data.oss-cn-shanghai.aliyuncs.com/1636793502840.jpg"));
//
//    }

    public static String getPicSign(String picUrl) {
        try {
            HttpResponse httpResponse = doGetWithResponse(new HttpGet(picUrl), null, null);
            InputStream content = httpResponse.getEntity().getContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 1024];
            int num = content.read(buffer);
            while (num != -1) {
                baos.write(buffer, 0, num);
                num = content.read(buffer);
            }
            baos.flush();
            String md5String = Md5Util.getMD5String(buffer);
            return md5String;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";

    }

    public static byte[] getPicByte(String picUrl) {
        try {
            HttpResponse httpResponse = doGetWithResponse(new HttpGet(picUrl), null, null);
            InputStream content = httpResponse.getEntity().getContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            long contentLength = httpResponse.getEntity().getContentLength();
            byte[] buffer = new byte[(int)contentLength];
            int num = content.read(buffer);
            while (num != -1) {
                baos.write(buffer, 0, num);
                num = content.read(buffer);
            }
            baos.flush();
            return buffer;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;

    }

    private static HttpResponse doGetWithResponse(HttpGet httpGet, HashMap<String, String> headers, HttpHost proxy) {
        try {
            if (headers != null) {
                for (Map.Entry<String, String> keyValue : headers.entrySet()) {
                    httpGet.addHeader(keyValue.getKey(), keyValue.getValue());
                }
            }

            CloseableHttpClient aDefault = getIgnoeSSLClient();
            RequestConfig.Builder builder = RequestConfig.custom()
                    .setConnectTimeout(3000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(3000);
            if (proxy != null) {
                builder.setProxy(proxy);
            }
            RequestConfig build = builder.build();
            httpGet.setConfig(build);
            return aDefault.execute(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    private static CloseableHttpClient getIgnoeSSLClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        //创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        return client;
    }


    public static String entityToString(HttpEntity entity) {
        try {
            String result = null;
            if (entity == null) {
                return null;
            }
            long lenth = entity.getContentLength();
            if (lenth != -1 && lenth < 2048) {
                result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            } else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8);
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while ((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
            return result;
        } catch (Exception ex) {
            Logger.error("entityToString", ex);
            return "";
        }

    }
}
